package models

// Product 结构体表示商品
type Product struct {
    ID       int     `json:"id"`
    Name     string  `json:"name"`
    Price    float64 `json:"price"`
    Quantity int     `json:"quantity"`
}

// 获取所有商品
func GetProducts() ([]Product, error) {
    rows, err := db.Query("SELECT id, name, price, quantity FROM products")
    if err != nil {
        return nil, err
    }
    defer rows.Close()

    var products []Product
    for rows.Next() {
        var p Product
        err := rows.Scan(&p.ID, &p.Name, &p.Price, &p.Quantity)
        if err != nil {
            return nil, err
        }
        products = append(products, p)
    }

    return products, nil
}

// 获取单个商品
func GetProductByID(id int) (Product, error) {
    var p Product
    err := db.QueryRow("SELECT id, name, price, quantity FROM products WHERE id = ?", id).Scan(&p.ID, &p.Name, &p.Price, &p.Quantity)
    if err != nil {
        return p, err
    }
    return p, nil
}

// 添加商品
func AddProduct(p Product) (int64, error) {
    stmt, err := db.Prepare("INSERT INTO products(name, price, quantity) VALUES(?, ?, ?)")
    if err != nil {
        return 0, err
    }
    defer stmt.Close()

    result, err := stmt.Exec(p.Name, p.Price, p.Quantity)
    if err != nil {
        return 0, err
    }

    return result.LastInsertId()
}

// 删除商品
func DeleteProduct(id int) (int64, error) {
    stmt, err := db.Prepare("DELETE FROM products WHERE id = ?")
    if err != nil {
        return 0, err
    }
    defer stmt.Close()

    result, err := stmt.Exec(id)
    if err != nil {
        return 0, err
    }

    // 获取删除的行数
    rowsAffected, err := result.RowsAffected()
    if err != nil {
        return 0, err
    }

    return rowsAffected, nil
}

